package com.qf.java2201.edu.ossservice.controller;

import com.aliyun.oss.OSS;
import com.qf.java2201.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @date 2022/5/28
 * @desc
 */
@RestController
@Api(tags = "阿里云存储服务通过服务器直传的方式")
@RequestMapping("/ossservice")
public class OssController {

    @Resource
    private OSS ossClient;


    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public R uploadPic(MultipartFile file) throws IOException {
        // 上传照片

        String filename = file.getOriginalFilename();  // 得到文件的名字

        InputStream inputStream = file.getInputStream();  // 将file 对象转为 输入流

        String objectName =   System.currentTimeMillis() +  filename.substring(filename.lastIndexOf("."));
        String dir = "img";

        // 阿里云存储  返回 上传之后的文件路径
        ossClient.putObject("qf2201",  dir+"/"+objectName, inputStream);

// 关闭OSSClient。
        ossClient.shutdown();
        String filePath = "https://qf2201.oss-cn-beijing.aliyuncs.com/img/"+objectName;

        return R.ok().data("url",filePath);
    }

}
